package com.amap.map2d.demo.util;

import android.content.Context;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by Jason on 2016/4/17.
 */
public class DBScan {
    private static Set<Point> pointSet = new HashSet<>();
    private static int minpts = 5;
    private static double radius = 0.01;

    public static void nostopping(ArrayList<Point> pointlist) {
        int clusterid = 1;
        for (Point point : pointlist) {
            if (point.isVisited()) {
                continue;
            }
            point.setVisited(true);
            List<Point> points = findset(point);
            if (points.size() <= minpts) {
                continue;
            } else {
                point.setCluster(clusterid);
                for (Point p : points) {
                    p.setVisited(true);
                    p.setCluster(point.getCluster());
                    List<Point> unpoints = findset(p);
                    if (unpoints.size() > minpts) {
                        for (Point up : unpoints) {
                            up.setVisited(true);
                            up.setCluster(point.getCluster());
                        }
                    }
                }
            }
            clusterid++;
        }
    }

    private static ArrayList<Point> findset(Point point) {
        ArrayList<Point> set = new ArrayList<>();
        Iterator<Point> iterator = pointSet.iterator();
        while (iterator.hasNext()) {
            Point next = iterator.next();
            if (Point.distance(next, point) < radius) {
                set.add(next);
            }
        }

        return set;
    }

    private static ArrayList<Point> pointlist = new ArrayList<>();

    public static Set<Point> getData(Context context) {
        try {
            Point.initpointset(pointSet, context);
            pointlist.addAll(pointSet);
            DBScan.nostopping(pointlist);
            System.out.println("DBScan2 打印结果");

            return pointSet;
        } catch (Exception e) {
            return null;
        }


    }


}